package com.yugu.park.config;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
@ServerEndpoint(value = "/websocket/{shopId}")
@Component
/**
 * 多个用户
 * @author 31631
 *
 */
public class WebSocketServer {

    /**
     * 静态变量，用来记录当前在线连接数。应该把它设计成线程安全的
     */

    private static int onlineCount = 0;

    /**
     * concurrent包的线程安全Map，用来存放每个客户端对应的MyWebSocket对象
     */
    private static ConcurrentHashMap<String, WebSocketServer> webSocketMap = new ConcurrentHashMap<>();

    /**
     * 与某个客户端的连接会话，需要通过它来给客户端发送数据
     */

    private Session session;
    private String shopId;

    public Session getSession() {
        return session;
    }

    public void setSession(Session session) {
        this.session = session;
    }

    public String getShopId() {
        return shopId;
    }

    public void setShopId(String shopId) {
        this.shopId = shopId;
    }

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "shopId") String shopId) {
        this.session = session;
        this.shopId = shopId;
        if(webSocketMap.containsKey(shopId)) {
            webSocketMap.remove(shopId);
            webSocketMap.put(shopId, this);
        }else {
            webSocketMap.put(shopId, this);
            addOnlineCount();           //在线数加1
        }
        //加入map
        try {
            sendMessage(String.valueOf(this.session.getQueryString()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        if (webSocketMap.containsKey(shopId)) {
            webSocketMap.remove(shopId);
            //从set中删除
            subOnlineCount();
        }
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        try {
            webSocketMap.get(shopId).sendMessage(message);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //群发消息
        /*for (String item : webSocketMap.keySet()) {
            try {
                webSocketMap.get(item).sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }*/
    }

    /**
     * 发生错误时调用
     *
     * @OnError
     */
    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }

    /**
     * 向客户端发送消息
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
        //this.session.getAsyncRemote().sendText(message);
    }

    /**
     * 通过shopId向客户端发送消息
     */
    public static void sendMessageTo(String shopId, String message) throws IOException {
        if(StringUtils.isNotEmpty(shopId)&&webSocketMap.containsKey(shopId)){
            webSocketMap.get(shopId).sendMessage(message);
        }
    }
    public static void sendMessageTo(String shopId, Object message) throws IOException {
        if(StringUtils.isNotEmpty(shopId)&&webSocketMap.containsKey(shopId)){
            webSocketMap.get(shopId).sendMessage(JSON.toJSONString(message));
        }
    }
    /**
     * 群发自定义消息
     */
    public static void sendInfo(String message) throws IOException {
        for (String item : webSocketMap.keySet()) {
            try {
                webSocketMap.get(item).sendMessage(message);
            } catch (IOException e) {
                continue;
            }
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }

}
